package net.jlibrary.account.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import net.jlibrary.account.domain.Employee;
import net.jlibrary.account.exception.AccountNotFoundException;
import net.jlibrary.account.exception.AccountPasswordErrorException;
import net.jlibrary.common.core.service.BaseManager;
import net.jlibrary.common.core.service.ISessionUser;
import net.jlibrary.common.core.service.IVerifyCode;
import net.jlibrary.common.project.domain.Group;
import net.jlibrary.common.project.domain.PermissionRole;
import net.jlibrary.common.tools.DateUtil;
import net.jlibrary.common.tools.MD5Encrypt;
import net.jlibrary.common.tools.StringUtil;
import net.jlibrary.curbparking.action.vo.EmployeeLoginVo;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class EmployeeManager extends BaseManager implements IEmployeeManager {
	private final Log log = LogFactory.getLog(getClass());

	@Resource
	private IVerifyCode verifyCode;
	@Resource
	private ISessionUser sessionUser;
	@Resource
	private HttpServletRequest request;

	@Override
	public String loginEmployee(EmployeeLoginVo vo) {
		log.info("用户 " + vo.getCode() + " 于 " + DateUtil.getCurrentTime() + " 登陆，登陆IP为 " + vo.getIp() + "，groupCode为 "
				+ vo.getGroupCode());

		if (!verifyCode.compareVerifyCode(vo.getVerifyCode(), request.getSession())) {
			// throw new VerifyCodeErrorException("验证码输入错误!!!");
		}
		Employee employee = new Employee();
		employee.setCode(vo.getCode());
		if (StringUtil.isNotBlank(vo.getGroupCode())) {
			employee.setGroup(new Group());
			employee.getGroup().setCode(vo.getGroupCode());
		}
		List<Employee> lists = dao.amountLists(employee, 1, new ArrayList<String>(), false);
		if (lists.size() == 0) {
			throw new AccountNotFoundException("登录名：" + vo.getCode() + " 不存在！");
		}
		employee = lists.get(0);

		if (!employee.getPassword().equals(MD5Encrypt.getInstance().encrypt(vo.getPassword()))) {
			throw new AccountPasswordErrorException("登录名 " + vo.getCode() + " 的密码不正确!");
		}
		employee.getGroup().getId();
		employee.setLoginTime(DateUtil.getCurrentTime());
		employee.setRefurbishTime(DateUtil.getCurrentTime());
		employee.setOnline(true);

		if (employee.getGroup().getParentGroup() != null) {
			employee.getGroup().getParentGroup().getCode();
		}
		sessionUser.setSessionAccount(employee);
		return employee.getRoles().iterator().next().getType().getCode();
	}

	@Override
	public List<PermissionRole> roles() {
		List<PermissionRole> list = dao.baseLists(new PermissionRole(), false);
		return list;
	}
}
